package net.telesing.tcmc.back.logic;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import net.telesing.tcmc.back.dao.CertificateDao;
import net.telesing.tcmc.back.dao.SectionDao;
import net.telesing.tcmc.back.model.*;
import net.telesing.tcmc.common.BaseDao;
import net.telesing.tcmc.common.LogicException;
import net.telesing.tcmc.core.web.AjaxBean;

/**
 * 接口Logic
 *
 * Created by Zmt on 2015/11/12.
 */
@IocBean
public class ApiLogic
{
    private static final String GET_NEW_DATA_SQL = "SELECT "
            + "MAX(VERSION_CODE) AS VERSION_CODE "
            + "FROM "
            + "(SELECT * FROM tsc_version_data WHERE FILE_TYPE=0 AND PRE_VERSION_CODE >=%s) vd";

    @Inject
    private BaseDao baseDao;
    
    @Inject
    private UserService userService;

    @Inject
    private SectionDao sectionDao;

    @Inject
    private CertificateDao certificateDao;
    
    @Inject
    private CertificateLogic certificateLogic;

    /**
     * 下载文件
     *
     * @param response
     * @param path
     * @param name
     * @return
     */
    public File download(HttpServletResponse response, String path, String name)
    {
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Content-Disposition", "attachment;filename=" + name);
        File file = new File(path);
        return file.exists() ? file : null;
    }

    /**
     * 检测APK是否有更新
     *
     * @param code
     * @return
     * @throws Exception
     */
    public Map<String, Object> checkUpdate(int code)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        Result result;
        try
        {
            if (0 != code)
            {
                DataModel dataModel = baseDao.executeSql(DataModel.class, String.format(GET_NEW_DATA_SQL, code));
                int vCode = dataModel.getvCode();
                if (0 != vCode)
                {
                    result = new Results().getRes(true, "有新版本可以更新！");
                    List<DataModel> list = new ArrayList<DataModel>();
                    list.add(baseDao.fetch(DataModel.class, Cnd.where("VERSION_CODE", "=", vCode)));
                    map.put("datas", list);
                }
                else
                    result = new Results().getRes(false, "当前已经是最新版本！");
            }
            else
                result = new Results().getRes(false, "版本号不能为空！");
        }
        catch (Exception e)
        {
            result = new Results().getRes(false, e.getMessage());
        }
        map.put("res", result);
        return map;
    }

    /**
     * 根据id获取号段信息
     *
     * @param id
     * @return
     * @throws Exception
     */
    public Map<String, Object> getSection(long id, String secret, int code)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        Result result = null;
        SectionModel sectionModel = null;
        String nullWord = null;
        boolean isParaNull = false;
        try
        {
            switch (code)
            {
                case 1:
                    if (0 != id)
                    {
                        sectionModel = baseDao.fetch(SectionModel.class, id);
                        nullWord = "该ID没有对应的号段";
                    }
                    else
                    {
                        isParaNull = true;
                        result = new Results().getRes(false, "ID不能为空");
                    }
                    break;
                case 2:
                    if (null != secret)
                    {
                        sectionModel = baseDao.fetch(SectionModel.class, Cnd.where("SECRET", "IS", secret));
                        nullWord = "该密文没有对应的号段";
                    }
                    else
                    {
                        isParaNull = true;
                        result = new Results().getRes(false, "密文不能为空");
                    }
                    break;
            }
            if (!isParaNull)
            {
                if (null != sectionModel)
                {
                    result = new Results().getRes(true, "");
                    List<SectionModel> list = new ArrayList<SectionModel>();
                    list.add(sectionModel);
                    map.put("datas", list);
                }
                else
                    result = new Results().getRes(false, nullWord);
            }
        }
        catch (Exception e)
        {
            result = new Results().getRes(false, e.getMessage());
        }
        map.put("res", result);
        return map;
    }

    /**
     * 根据用户名、密码获取码段
     *
     * @param userName
     * @param pwd
     * @return
     */
    public Map<String, Object> getSection(String userName, String pwd)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        Result result = null;
        try
        {
            long uid = userService.login(userName, pwd).getId();
            List<SectionModel> list = sectionDao.query(SectionModel.class, Cnd.where("UID", "=", uid));
            if (null != list && 0 < list.size())
            {
                result = new Results().getRes(true, "");
                map.put("data", list);
                map.put("uid", uid);
            }
        }
        catch (LogicException e)
        {
            result = new Results().getRes(false, "用户名或密码错误！");
        }
        map.put("res", result);
        return map;
    }

    /**
     * 根据用户名、密码、码段、证书类型申请证书
     *
     * @param userName
     * @param pwd
     * @param sName
     * @param cType
     * @return
     */
    public Map<String, Object> getCertificate(String userName, String pwd, String sName, int cType, HttpServletRequest httpServletRequest)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        Result result = null;
        try
        {
            long uid = userService.login(userName, pwd).getId();
            SectionModel section = sectionDao.fetch(Cnd.where("NAME", "=", sName));
            if (null != section)
            {
                if (uid == section.getUid())
                {
//                    List<CertificateModel> list = certificateDao.query(CertificateModel.class, Cnd.where("SID", "=", section.getId()).and("TYPE", "=", cType));
//                    if (null != list && 0 < list.size())
//                    {
//                        result = new Results().getRes(true, "");
//                        map.put("data", list);
//                    }
//                    else
//                        result = new Results().getRes(false, "该码段下暂无证书！");
                    final CertificateModel cer = new CertificateModel();
                    cer.setSid(section.getId());
                    cer.setType(cType);
                    cer.setOrigin(CertificateModel.FROM_API);
                    cer.setmOrg("empty");
                    AjaxBean ajaxBean = certificateLogic.apply(uid, cer, httpServletRequest);
                    if (ajaxBean.isOk())
                    {
                        List<CertificateModel> list = new ArrayList<CertificateModel>() {
                            {
                                add(cer);
                            }
                        };
                        result = new Results().getRes(true, "");
                        map.put("data", list);
                    }
                    else
                        result = new Results().getRes(false, ajaxBean.getMsg());
                }
                else
                    result = new Results().getRes(false, "该用户权限不足！");
            }
            else
                result = new Results().getRes(false, "该码段不存在！");
        }
        catch (LogicException e)
        {
            result = new Results().getRes(false, "用户名或密码错误！");
        }
        map.put("res", result);
        return map;
    }

    /**
     * 根据码段获取码段详情
     *
     * @param section
     * @return
     */
    public Map<String, Object> getSection(String section)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        Result result = null;
        final SectionModel sectionModel = sectionDao.fetch(Cnd.where("NAME", "=", section));
        if (sectionModel == null)
            result = new Results().getRes(false, "该码段不存在！");
        else
        {
            if (sectionModel.getSource() == null)
                sectionModel.setSource("");
            if (sectionModel.getSkipPath() == null)
                sectionModel.setSkipPath("");
            List<SectionModel> list = new ArrayList<SectionModel>() {{
                    add(sectionModel);
                }
            };
            map.put("data", list);
            result = new Results().getRes(true, "");
        }
        map.put("res", result);
        return map;
    }
    
}
